/**
 * Created with JetBrains PhpStorm.
 * User: Sergey
 * Date: 17.07.13
 * Time: 16:23
 * To change this template use File | Settings | File Templates.
 */

var schemeObjectsArr = [];
var schemeObjectsField = null;
var solutionItems = [];
var selectedSchemeObjectArea = null;
var selectedListBoxItemIndex = -1;
var selectedListViewItemIdentifier = -1;
var solutionSchemeCanvas = null;
var solutionSchemeItemsListView = null;

var selectedAreaOnImage = null;
var removeSchemeObjectAreaButton = null;

function refreshSchemeItemsListView() {
    solutionSchemeItemsListView.jqxListBox({
        source:solutionItems,
        displayMember:'name',
        valueMember:'id',
        selectedIndex:selectedListBoxItemIndex,
        width:280,
        height:250,
        theme:''
    });
}

function onSelectChangeAreaInCanvas(image, params) {
    removeButtonPositioning();
}

function onSelectedEndAreaInCanvas(image, params) {
    removeButtonPositioning();

    if (params.width > 0 && params.height > 0) {
        addOrUpdateItemToSchemeObjects(selectedListViewItemIdentifier, params);
    } else {
        refreshSchemeItemsListView();
        if (selectedListBoxItemIndex != -1 && selectedListBoxItemIndex > 0) {
            var id = solutionSchemeItemsListView.jqxListBox('getItem', selectedListBoxItemIndex).value;
            selectedSchemeObjectArea = getSchemeObjectById(id);
            enableIASPluginAndShowSelectedArea();
        } else {
            enableIASPlugin();
            removeSchemeObjectAreaButton.hide();
        }
    }
}

function addOrUpdateItemToSchemeObjects(id, params) {
    var oldObject = null;
    for (var i = 0; i < schemeObjectsArr.length; i++)
        if (schemeObjectsArr[i].id == id)
            oldObject = schemeObjectsArr[i];
    if (oldObject != null) {
        var newCopySchemeObjects = [];
        for (var i = 0; i < schemeObjectsArr.length; i++)
            if (schemeObjectsArr[i] != oldObject)
                newCopySchemeObjects.push(schemeObjectsArr[i]);
        schemeObjectsArr = newCopySchemeObjects;
    }
    schemeObjectsArr.push(buildSchemeObject(id, params));
    outputSchemeObjectsData();
}

function removeItemFromSchemeObject(id) {
    var tempArray = [];
    for (var i = 0; i < schemeObjectsArr.length; i++) {
        if (schemeObjectsArr[i].id == id) continue;
        tempArray.push(schemeObjectsArr[i]);
    }
    schemeObjectsArr = tempArray;
    outputSchemeObjectsData();
}

function buildSchemeObject(id, params) {
    var obj = {
        id:id.toString(),
        x1:params.x1.toString(),
        y1:params.y1.toString(),
        x2:params.x2.toString(),
        y2:params.y2.toString()
    };
    return obj;
}

function enableIASPlugin() {
    solutionSchemeCanvas.imgAreaSelect({
        handles:true,
        onSelectChange:onSelectChangeAreaInCanvas,
        onSelectEnd:onSelectedEndAreaInCanvas
    });
}

function enableIASPluginAndShowSelectedArea() {
    solutionSchemeCanvas.imgAreaSelect({
        handles:true,
        onSelectChange:onSelectChangeAreaInCanvas,
        onSelectEnd:onSelectedEndAreaInCanvas,
        x1:selectedSchemeObjectArea.x1,
        y1:selectedSchemeObjectArea.y1,
        x2:selectedSchemeObjectArea.x2,
        y2:selectedSchemeObjectArea.y2
    });
}

function getSchemeObjectById(id) {
    for (var i = 0; i < schemeObjectsArr.length; i++)
        if (schemeObjectsArr[i].id == id)
            return schemeObjectsArr[i];
    return null;
}

function outputSchemeObjectsData() {
    cleanSchemeObjectsArr();
    if (schemeObjectsField != null) {
        var data = JSON.stringify(schemeObjectsArr);
        schemeObjectsField.val(data);
    }
}

function cleanSchemeObjectsArr() {
    var tempArray = [];
    for (var i = 0; i < schemeObjectsArr.length; i++) {
        var coincidence = false;
        for (var j = 0; j < solutionItems.length; j++) {
            if (schemeObjectsArr[i].id == solutionItems[j].id)
                coincidence = true;
        }
        if (coincidence && schemeObjectsArr[i].id != "")
            tempArray.push(schemeObjectsArr[i])
    }
    schemeObjectsArr = tempArray;
}

function removeButtonPositioning() {
    selectedAreaOnImage = $('.imgareaselect-selection').parent();
    removeSchemeObjectAreaButton.hide();
    removeSchemeObjectAreaButton.show();
    removeSchemeObjectAreaButton.position({
        my:'left',
        at:'right top',
        of:selectedAreaOnImage
    });
}

$(function () {
    var attentionMessage = 'Рекомендуемый размер картинки не более 755 пикселей в ширину.';
    $('tr#tr_PROPERTY_46 td:eq(1)').append('<b style="color: red;">* ' + attentionMessage + '</b>');
    var loadFileButton = $('span[id^="bx_file_prop_46"].add-file-popup-btn');
    loadFileButton.attr('title', attentionMessage);
    loadFileButton.tooltip();

    // Get filed for storing data
    schemeObjectsField = $('tr#tr_PROPERTY_47 textarea[name^="PROP_47__"]');
    schemeObjectsField.css('width', '400px');
    $('tr#tr_PROPERTY_47').hide();

    // Load created object
    if (schemeObjectsField.val() != null && schemeObjectsField.val() != '')
        schemeObjectsArr = JSON.parse(schemeObjectsField.val());

    // Create additional widgets
    $('#cedit1_edit_table').append('' +
        '<tr><td colspan="2" style="text-align: center;">Полотно для построения интерактивной карты решения</td> </tr>' +
        '<tr>' +
        '  <td colspan="2" class="adm-detail-valign-top adm-detail-content-cell-l">' +
        '    <table style="text-align: left;"> ' +
        '      <tr>' +
        '        <td style="vertical-align: top;">' +
        '          <span>Список товаров решения</span>' +
        '          <div id="solution_scheme_items_listview"></div>' +
        '          <img id="remove_scheme_object_button" src="/bitrix/modules/ss_constructor/admin/close_button.png" ' +
        '            width="32" title="Удалить отметку" ' +
        '            style="position: absolute; display: block; z-index:100;" /> ' +
        '        </td>' +
        '        <td><img id="solution_scheme_canvas" alt="Canvas for solution scheme "></td>' +
        '      </tr> ' +
        '    </table>' +
        '  </td>' +
        '</tr>');
    var imgSource = $('#tr_PROPERTY_46 a[target="_blank"]').attr('href');
    solutionSchemeCanvas = $('img#solution_scheme_canvas');
    solutionSchemeCanvas.attr('src', imgSource);
    solutionSchemeCanvas.css('maxWidth', '755px');

    // Get list of products
    var rowsSolutionItems = $('tr#tr_PROPERTY_45 table tr td').toArray();
    for (var i = 0; i < rowsSolutionItems.length; i++) {
        var _id = $('input[name^="PROP"]', rowsSolutionItems[i]).val();
        var _name = $('span', rowsSolutionItems[i]).text();
        if (_id != null && _id != '' && _name != null && _name != '') {
            var productItemInstance = {
                id:_id,
                name:_name
            };
            solutionItems.push(productItemInstance);
        }
    }

    // get list view
    solutionSchemeItemsListView = $('#solution_scheme_items_listview');
    // Show list of products
    refreshSchemeItemsListView();
    // handle selecting new object
    solutionSchemeItemsListView.bind('select', function (event) {
        // get selected item index and selected product identifier
        selectedListBoxItemIndex = args.index;
        var item = solutionSchemeItemsListView.jqxListBox('getItem', event.args.index);
        selectedListViewItemIdentifier = item.value;

        selectedSchemeObjectArea = getSchemeObjectById(item.value);
        if (selectedSchemeObjectArea != null) {
            enableIASPluginAndShowSelectedArea();
            removeButtonPositioning();
        } else {
            solutionSchemeCanvas.imgAreaSelect({remove:true});
            enableIASPlugin();
            removeSchemeObjectAreaButton.hide();
        }
        removeButtonPositioning();
    });

    // Refresh scheme object
    outputSchemeObjectsData();

    // If user leave "Solution scheme" tab reset image area select
    $('.adm-detail-tabs-block.adm-detail-tabs-block-settings span:not(#tab_cont_cedit1)').click(function () {
        if (selectedSchemeObjectArea != null) {
            solutionSchemeCanvas.imgAreaSelect({remove:true});
            enableIASPlugin();
        }
    });

    // If user open "Solution scheme" tab active image area select
    $('.adm-detail-tabs-block.adm-detail-tabs-block-settings span#tab_cont_cedit1').click(function () {
        if (selectedSchemeObjectArea != null)
            enableIASPluginAndShowSelectedArea();
    });

    removeSchemeObjectAreaButton = $('#remove_scheme_object_button');
    removeSchemeObjectAreaButton.css({cursor:'pointer'});
    removeSchemeObjectAreaButton.hide();
    removeSchemeObjectAreaButton.tooltip();
    removeSchemeObjectAreaButton.click(function () {
        if (selectedSchemeObjectArea != null) {
            // delete item
            removeItemFromSchemeObject(selectedSchemeObjectArea.id);
            outputSchemeObjectsData();
            // stop showing deleted item
            solutionSchemeCanvas.imgAreaSelect({remove:true});
            enableIASPlugin();
            // after deleting hide remove button
            removeSchemeObjectAreaButton.hide();
        }
    });
});